package com.twu.biblioteca;

import java.io.*;
import java.util.ArrayList;
import java.util.logging.Logger;


public class BooksLibraryController {

    private BooksLibrary booksLibrary;              // book library object
    private String BOOK_LIST_FILE="bookList.txt";
    final String ERROR_MESSAGE="Sorry,the system has encountered an error. Please try again later";

    private Logger logger;

    BooksLibraryController(String bookListFileName,Logger logger)
    {
        BOOK_LIST_FILE=bookListFileName;
        this.logger=logger;

        booksLibrary=new BooksLibrary(BOOK_LIST_FILE,logger);
    }

    void displayAllBooksToConsole()
    {
        displayHeaderInformation();

        ArrayList<Book> books= booksLibrary.getAllBooks();
        for(Book b:books)
        {
            System.out.println(b.getId()+"  | "+b.getName()+" | "+b.getAvailability());
        }
        System.out.println();
    }

    void displayHeaderInformation()
    {
        System.out.println("List of books in the booksLibrary:");
        System.out.println("---------------------------");
        System.out.println("Id |  Name  |  Availability");
        System.out.println("---------------------------");
    }

    void reserveBookForMember(BufferedReader reader)
    {
        String id=readBookIdFromUser(reader);
        if(booksLibrary.isBookAvailable(id)) // book can be reserved
        {
            booksLibrary.checkOut(id);
            System.out.println("Thank you! Enjoy the book!\n");
        }
        else   // book has already been reserved by someone else or the booksLibrary does not have this book
        {
            System.out.println("Sorry,the book is not available yet"+"\n");
        }
    }

    void returnBookFromMember(BufferedReader reader)
    {
        String id=readBookIdFromUser(reader);

        if(booksLibrary.hasBook(id) && !booksLibrary.isBookAvailable(id)) // valid return of a book
        {
            booksLibrary.checkIn(id);
            System.out.println("The book has been successfully returned! Thank you!\n");
        }
        else  // the book id is invalid
        {
            System.out.println("Please enter a valid book id!\n");
        }
    }

    void saveBooksToFile()
    {
        booksLibrary.saveToFile();
    }

    private String readBookIdFromUser(BufferedReader reader)
    {
        String id="";
        System.out.print("Please enter the id of the book:");
        try
        {
            id=reader.readLine();
        }
        catch(IOException e)
        {
            logger.severe(e.getMessage());
            System.out.println(ERROR_MESSAGE+"\n");
            System.exit(1);
        }
        return id;
    }



}
